import { Row, Col, Select, PageHeader, Input, Divider, Form, TimePicker, Button, Modal, message } from "antd";
import { MinusCircleOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from 'react';
import axios from "axios";
import { Navigate, useLocation } from "react-router-dom";
import moment from 'moment';
import { Link, useNavigate } from 'react-router-dom';

const defaultMethodGroup = [
    {
        key: 1,
        name: 1,
        items: [
            {
                name: 1,
                key: 1,
            },
            {
                name: 2,
                key: 2,
            },
            {
                name: 3,
                key: 3,
            }
        ]
    },
    {
        key: 2,
        name: 2,
        items: [
            {
                name: 1,
                key: 1,
            },
            {
                name: 2,
                key: 2,
            },
            {
                name: 3,
                key: 3,
            }
        ]
    },
]

const defaultAccessoryGroup = [1, 2, 3];


export default function EditProduct() {
    let location = useLocation();
    const navigate = useNavigate();
    const [dataSource, setDataSource] = useState(location.state.data);
    const [form] = Form.useForm();
    const [methodGroup, setMethodGroup] = useState(defaultMethodGroup);
    const [accessoryGroup, setAccessoryGroup] = useState(defaultAccessoryGroup);
    const [currentVersion, setCurrentVersion] = useState();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const tenantId = location.state.data.tenantId;
    const createdBy = location.state.data.auditing.createdBy;
    const id = location.state.data.id;

    useEffect(() => {
        queryShop();
    }, []);

    function queryShop() {
        const instance = axios.create({
            headers: { "tenantId": tenantId, "userId": createdBy }
        })
        instance.get('/product/' + id)
            .then((res) => {
                if (res.data.status.code === 0) {
                    console.log(res.data.data)
                    setAccessoryGroup(res.data.data.accessoryGroups)
                    // setMethodGroup(res.data.data.methodGroups)
                    setCurrentVersion(res.data.data.version)
                }
            })
    }

    const accessoryDataFormat = (values) => {
        let accessoryGroups = [];
        accessoryGroup.forEach((item, index) => {
            accessoryGroups = [
                {
                    "name": '配菜',
                    "options": [
                        {
                            "name": values[`accessory_${index}`],
                            "unitPrice": values[`unitPrice_${index}`],
                            "unitOfMeasure": values[`unitOfMeasure_${index}`],
                        }
                    ]
                }
            ];
        })
        return accessoryGroups;
    }

    const methodDataFormat = (values) => {
        let methodGroups = [];
        methodGroup.forEach((item, index) => {
            item.items.forEach((items, idx) => {
                methodGroups = [
                    {
                        "name": values[`methodGroup_${index}`],
                        "options": [
                            {
                                "name": values[`method_${index}_${idx}`]
                            }
                        ]
                    }
                ]
            })
        })
        return methodGroups;
    }
    const creaseMethodGroup = () => {
        const key = methodGroup.length;
        const newArr = [...methodGroup];
        newArr.push({
            key: key,
            name: 2,
            items: [
                {
                    name: 1,
                    key: 1,
                },
                {
                    name: 2,
                    key: 2,
                },
                {
                    name: 3,
                    key: 3,
                }
            ]
        });
        setMethodGroup(newArr);
    }

    //删除做法组
    const deleteMethodGroup = (index) => {
        const newArr = [...methodGroup];
        newArr.forEach(function (item, i) {
            console.log(i)
            if (i === index) {
                newArr.splice(i, 1);
            }
        })
        setMethodGroup(newArr)
    }
    //删除做法
    const deleteMethod = (index, i) => {
        const newArr = [...methodGroup];
        newArr.forEach(function (item, idx) {
            if (idx === index) {
                newArr[index].items.splice(idx, 1)
            }
        })
        setMethodGroup(newArr)
    }

    //添加做法
    const creaseMethod = (index) => {
        const newArr = [...methodGroup];
        const itemsLen = newArr[index].items.length;
        newArr[index].items.push({
            key: itemsLen + 1,
            name: itemsLen + 1
        })
        setMethodGroup(newArr)
    }

    //添加加料
    const creaseAccessory = () => {
        const newArr = [...accessoryGroup];
        newArr.push(newArr.length + 1);
        setAccessoryGroup(newArr);
    }

    //删除加料
    const deleteAccessory = (index) => {
        const newArr = [...accessoryGroup];
        newArr.forEach(function (item, idx) {
            if (idx === index) {
                newArr.splice(idx, 1)
            }
        });
        setAccessoryGroup(newArr)
    }

    const onFinish = (values) => {
        console.log(values)
        const instance = axios.create({
            headers: { "tenantId": 500, "userId": 11000 }
        })
        instance.put('/product/' + id, {
            "description": values.description,
            "increaseSalesQuantity": values.increaseSalesQuantity,
            "minSalesQuantity": values.minSalesQuantity,
            "name": values.productName,
            "unitOfMeasure": values.unitOfMeasure,
            "unitPrice": values.unitPrice,
            "version": currentVersion
        }
        ).then((res) => {
            if (res.data.status.code === 0) {
                console.log(res)
                queryShop();
                return;
            }
            error();
        });
    };

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = () => {
        setIsModalVisible(false);
        navigate('/product');
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const error = () => {
        message.error('菜品信息已被更改，更新失败！');
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    form.setFieldsValue({
        productName: dataSource.name,
        unitPrice: dataSource.unitPrice,
        unitOfMeasure: dataSource.unitOfMeasure,
        minSalesQuantity: dataSource.minSalesQuantity,
        increaseSalesQuantity: dataSource.increaseSalesQuantity,
        description: dataSource.description,
    })
    // console.log(accessoryGroup)
    return (
        <>
            <Row className="title-row">
                <Col>
                    <PageHeader
                        className="site-page-header"
                        onBack={() => navigate('/product')}
                        title={dataSource.name}
                    />
                </Col>
            </Row>
            <Form
                form={form}
                name="editForm"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
            >
                <Row>
                    <Col span={24}>
                        <Divider orientation="left"><span style={{ "fontWeight": "bold", "fontSize": "18px" }}>通用信息</span></Divider>
                    </Col>
                </Row>
                <Row>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-name">菜品名</span></Divider>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="productName"
                            rules={[
                                {
                                    type: 'string',
                                    required: true,
                                    whitespace: true,
                                    message: '输入不能为空',
                                },
                                {
                                    max: 20,
                                    message: '菜品名的最大长度为20字符',
                                },
                            ]}
                        >
                            <Input style={{
                                "width": "800px",
                                "borderTopRightRadius": "8px",
                                "borderBottomRightRadius": "8px",
                                "borderLeft": "none",
                                "marginLeft": "62px",
                            }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col>
                        <Divider><span className="span-color">菜品单价</span></Divider>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="unitPrice"
                        >
                            <Input className="unit-price" />
                        </Form.Item>
                    </Col>
                    <Col>
                        <Divider><span className="span-shop-name">计量单位</span></Divider>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="unitOfMeasure"
                        >
                            <Input className="unit-price" />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-color">起售价</span></Divider>
                    </Col>
                    <Col span={10}>
                        <Form.Item
                            name="minSalesQuantity"
                        >
                            <Input style={{
                                "width": "180px",
                                "borderTopRightRadius": "8px",
                                "borderBottomRightRadius": "8px",
                                "borderLeft": "none",
                                "marginLeft": "-28px",
                            }}
                            />
                        </Form.Item>
                    </Col>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-color">增售量</span></Divider>
                    </Col>
                    <Col span={10}>
                        <Form.Item
                            name="increaseSalesQuantity"
                        >
                            <Input style={{
                                "width": "180px",
                                "borderTopRightRadius": "8px",
                                "borderBottomRightRadius": "8px",
                                "borderLeft": "none",
                                "marginLeft": "-28px",
                            }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col style={{ "width": "32px" }}>
                        <Divider><span className="span-shop-address">描述</span></Divider>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="description"
                        >
                            <Input style={{
                                "width": "800px",
                                "borderTopRightRadius": "8px",
                                "borderBottomRightRadius": "8px",
                                "borderLeft": "none",
                                "marginLeft": "62px",
                            }}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={18}>
                        <Divider orientation="left"><span style={{ "fontWeight": "bold", "fontSize": "18px" }}>做法</span></Divider>
                    </Col>
                    <Col>
                        <Button
                            className="method-group-btn"
                            onClick={creaseMethodGroup}
                        >
                            添加做法组
                        </Button>
                    </Col>
                </Row>
                {
                    methodGroup.map((item, index) => {
                        return (
                            <>
                                {
                                    item.items.map((its, i) => {
                                        if (i === 0) {
                                            return (
                                                <Row>
                                                    <Col span={9}>
                                                        <Form.Item label='做法组名' name={`methodGroup_${index}`}>
                                                            <Input />
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={1}>
                                                        <MinusCircleOutlined style={{ fontSize: '200%', color: "gray" }} onClick={() => {
                                                            deleteMethodGroup(index)
                                                        }} />
                                                    </Col>
                                                    <Col span={13}>
                                                        <Form.Item label={`做法${i + 1}`} name={`method_${index}_${i}`}>
                                                            <Input />
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={1}>
                                                        <MinusCircleOutlined style={{ fontSize: '200%', color: "gray" }} onClick={() => {
                                                            deleteMethodGroup(index)
                                                        }} />
                                                    </Col>
                                                </Row>
                                            )
                                        } else {
                                            return (
                                                <Row>
                                                    <Col span={10}>
                                                    </Col>
                                                    <Col span={13}>
                                                        <Form.Item label={`做法${i + 1}`} name={`method_${index}_${i}`}>
                                                            <Input />
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={1}>
                                                        <MinusCircleOutlined style={{ fontSize: '200%', color: "gray" }} onClick={() => {
                                                            deleteMethod(index, i)
                                                        }} />
                                                    </Col>
                                                </Row>
                                            )
                                        }
                                    })
                                }
                                <Row>
                                    <Col>
                                        <Button
                                            className="method-btn"
                                            onClick={() => {
                                                creaseMethod(index);
                                            }}
                                        >
                                            添加做法
                                        </Button>
                                    </Col>
                                </Row>
                            </>
                        )
                    })
                }
                <Row>
                    <Col span={18}>
                        <Divider orientation="left"><span style={{ "fontWeight": "bold", "fontSize": "18px" }}>加料</span></Divider>
                    </Col>
                </Row>
                {
                    accessoryGroup.map((item, index) => {
                        return (
                            <>
                                <Row>
                                    <Col span={9}>
                                        <Form.Item label='加料名' name={`accessory_${index}`}>
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={6} offset={1}>
                                        <Form.Item label='单价' name={`unitPrice_${index}`}>
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={6} offset={1}>
                                        <Form.Item label='计量单位' name={`unitOfMeasure_${index}`}>
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={1}>
                                        <MinusCircleOutlined style={{ fontSize: '200%', color: "gray" }} onClick={() => {
                                            deleteAccessory(index);
                                        }} />
                                    </Col>
                                </Row>
                            </>
                        )
                    })
                }
                <Row>
                    <Col>
                        <Button
                            className="accessory-btn"
                            onClick={() => {
                                creaseAccessory();
                            }}
                        >
                            添加加料
                        </Button>
                    </Col>
                </Row>
                <Button onClick={() => {
                    showModal()
                }}
                >
                    取消</Button>
                <Modal
                    title="确认丢失修改的内容"
                    visible={isModalVisible}
                    onOk={handleOk}
                    onCancel={handleCancel}
                    okText="返回主界面"
                    cancelText="回到当前页面"
                    okType=""
                >
                    <p style={{ "textAlign": "center" }}>所有修改均会丢失，请确认？</p>
                </Modal>
                <Button
                    onClick={() => {
                        window.history.back(-1);
                        // onFinish()
                    }}
                    style={{
                        "backgroundColor": "rgb(244,188,72)"
                    }}
                >
                    <Link to={'/product'}>保存并返回</Link></Button>

                <Button
                    htmlType="submit"
                    style={{
                        "backgroundColor": "rgb(244,188,72)"
                    }}
                >
                    保存</Button>
            </Form>
        </>
    )
}